package com.yanqu.road.server.manger.config;

import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.thread.ThreadTaskManger;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.minibind.WechatBindQueryTask;
import com.yanqu.road.server.manger.ChannelConfigMgr;

import java.util.HashMap;
import java.util.Map;

public class WechatBindMgr extends TempMgr {
    private static Map<String, String> gameIdMap = new HashMap<>();
    private static ThreadTaskManger threadTaskManger;

    @Override
    public boolean init() throws Exception {
        addChannelConfigReloadListener();
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        initGameIdMap();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        if (null == threadTaskManger) {
            threadTaskManger = new ThreadTaskManger(1, this.getClass().getSimpleName());
        }
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    private void addChannelConfigReloadListener() {
        ChannelConfigMgr.addReloadListener(() -> {
            initGameIdMap();
        });
    }

    public static void initGameIdMap() {
        Map<String, String> tempGameIdMap = new HashMap<>();
        for (String attrs : ChannelConfig.WX_BIND_PLATFORM_GAME_ID.split("\\|")) {
            String[] split = attrs.split("=");
            String appId = split[0];
            String gameId = split[1];
            tempGameIdMap.put(appId, gameId);
        }
        gameIdMap = tempGameIdMap;
    }

    public static String getMiniGameId(String appId) {
        if (gameIdMap.containsKey(appId)) {
            return gameIdMap.get(appId);
        }
        return "";
    }

    public static void addUrlQueryTask(int protocol, GamePlayer gamePlayer) {
        threadTaskManger.addTask(0, new WechatBindQueryTask(protocol, gamePlayer));
    }
}
